/*
 * Copyright 2013-2015 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.util.JSONPObject;

import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2015-10-8下午10:43:05
 * @since 1.0
 * @see
 */
public class BaseController {
	protected Log log = LogFactory.getLog(getClass());
	/**
	 * 根据callback判断是否是jsonp返回还是json返回
	 * @author max.zheng
	 * @create 2015-10-2上午12:56:19
	 * @modified by
	 * @param callback
	 * @param r
	 * @return
	 */
	protected Object returnCheck(String callback, ResultMessage r) {
		if (StringUtils.isNotBlank(callback)) {
			return new JSONPObject(callback,r);  
		}else {
			return r;
		}
	}
	
	/**
	 * 将字符串内容返回前端
	 * 
	 * @author max.zheng
	 * @create 2016-3-10下午10:12:11
	 * @modified by
	 * @param request
	 * @param response
	 * @param content
	 */
	protected void returnStringContent(HttpServletRequest request,
			HttpServletResponse response,String content) {
		try {
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			out.print(content);
			out.close();
		} catch (IOException e) {
			log.error("basecontroller returnStringContent error",e);
		}
	}
	
	/**
	 * 直接输出字符串成json对象，前提字符串是json内容
	 * @param response		
	 * @param data			json字符串对象内容
	 * @return
	 */
	protected void returnStrJson(HttpServletResponse response,String dataJson) {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out = response.getWriter();
			out.print(dataJson);
			out.close();
		} catch (IOException e) {
			log.error("basecontroller returnStringJson error",e);
		}
	}
}
